package fid

import (
	"encoding/gob"
	"fmt"
	"reflect"
	"sync"
	"time"

	"gitee.com/gaoguangting/fid/session"
)

const (
	SESSION_KEY_USER = "__session_user"
)

type (
	SessionUser struct {
		LastAccessTime time.Time
		Privileges     []string // 权限编码
		UserWrapper    []byte
	}
)

func (f *Fid) checkSessionUser(sessionStore session.Store) (*SessionUser, bool, error) {
	sUserWrap := sessionStore.Get(SESSION_KEY_USER)
	if sUserWrap == nil {
		return nil, false, nil
	}
	if sUser, b := sUserWrap.(SessionUser); !b {
		return nil, false, fmt.Errorf("unkown __session_user value")
	} else {
		return &sUser, true, nil
	}
}

var gobRegisterMap = map[string]bool{}
var gobLock sync.RWMutex

func gobRegister(data interface{}) {
	gobLock.Lock()
	defer gobLock.Unlock()
	typ := reflect.TypeOf(data)
	if typ.Kind() == reflect.Ptr {
		typ = typ.Elem()
	}
	typName := typ.PkgPath() + "." + typ.Name()
	if _, ok := gobRegisterMap[typName]; ok {
		return
	}
	gob.Register(data)
	gobRegisterMap[typName] = true
}

func init() {
	gobRegister(time.Time{})
	gobRegister([]byte{})
	gobRegister(SessionUser{})
}
